# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import MySQLdb
import MySQLdb.cursors


class QunarPipeline(object):
    def __init__(self, dbpool):
        self.dbpool = dbpool

    @classmethod
    def from_settings(cls, settings):
        dbargs = dict(
            host=settings['MYSQL_HOST'],
            db=settings['MYSQL_DBNAME'],
            user=settings['MYSQL_USER'],
            passwd=settings['MYSQL_PASSWD'],
            charset='utf8',
            cursorclass=MySQLdb.cursors.DictCursor,
            use_unicode=True,
        )
        dbpool = adbapi.ConnectionPool('MySQLdb', **dbargs)
        return cls(dbpool)

    def process_item(self, item, spider):
        d = self.dbpool.runInteraction(self._do_upinsert, item, spider)
        d.addErrback(self._handle_error, item, spider)
        d.addBoth(lambda _: item)
        return d

    def _do_upinsert(self, conn, item, spider):

        conn.execute("""
                        select 1 from spot where name = %s
                """, (item['name'],))
        ret = conn.fetchone()
        if not ret:
            conn.execute("""
                            insert into spot(url, name, address, description, score, comment_num, ticket_price, available_time, suggest_time)
                            values(%s, %s, %s, %s, %s, %s, %s, %s, %s)
                        """, (item['url'], item['name'], item['address'], item['description'], item['score'], item['comment_num'],
                              item['ticket_price'], item['available_time'], item['suggest_time']))

    def _handle_error(self, failue, item, spider):
        import pdb
        pdb.set_trace()
        print '-------------------------------------'
        log.err(failure)
